package cn.chitanda.weather.utile

import android.annotation.SuppressLint
import android.content.Context
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle

class LocationUtil(val context: Context) {
    private var location: Location? = null
    private var locationManager: LocationManager? = null
    private val locationListener = object : LocationListener {
        override fun onLocationChanged(location: Location?) {
            location?.accuracy
            location?.let { setLocation(it) }
        }

        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
        }

        override fun onProviderEnabled(provider: String?) {
        }

        override fun onProviderDisabled(provider: String?) {
        }

    }

    init {
        getLocation()
    }

    companion object {
        private var INSTANCE: LocationUtil? = null
        fun getInstance(context: Context): LocationUtil {
            return INSTANCE ?: synchronized(this) {
                LocationUtil(context).also { INSTANCE = it }
            }
        }
    }

    @SuppressLint("MissingPermission")
    private fun getLocation() {
        locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val providers = locationManager?.allProviders
        val locationProvider = when {
            providers?.contains(LocationManager.NETWORK_PROVIDER)!! -> {
                LocationManager.NETWORK_PROVIDER
            }
            providers.contains(LocationManager.GPS_PROVIDER) -> {
                LocationManager.GPS_PROVIDER
            }
            else -> {
                return
            }
        }

        val lastKnowLocation = locationManager?.getLastKnownLocation(locationProvider)
        if (lastKnowLocation != null) setLocation(lastKnowLocation)
        locationManager?.requestLocationUpdates(locationProvider, 0, 0f, locationListener)
    }

    fun showLocation() = location

    private fun setLocation(location: Location) {
        this.location = location
    }

    fun removeLocationUpdatesListener() {
        if (locationManager != null) {
            INSTANCE = null
            locationManager?.removeUpdates(locationListener)
        }
    }
}